﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Swirebev.PhotoDownload.Common;
using Swirebev.PhotoDownload.Model;

namespace Swirebev.PhotoDownload.Cloud
{
	public class HttpDownload
	{
		/// <summary>
		/// 下载照片文件
		/// </summary>
		/// <param name="uri"></param>
		/// <param name="photoData"></param>
		public static void DownloadFile(Uri uri, PhotoData photoData)
		{
			try
			{
				HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
				request.Method = "get";
				request.KeepAlive = true;

				using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
				{
					switch (response.StatusCode)
					{
						case HttpStatusCode.OK:
							using (Stream responseStream = response.GetResponseStream())
							using (MemoryStream ms = new MemoryStream())
							{
								byte[] buffer = new byte[102400];
								int readedSize;
								while ((readedSize = responseStream.Read(buffer, 0, buffer.Length)) > 0)
								{
									ms.Write(buffer, 0, readedSize);
								}
								photoData.DownloadStatus = PhotoDownloadStatus.DownloadSuccess;
								photoData.PhotoBuffer = ms.ToArray();
							}
							break;
						case HttpStatusCode.NotFound:
							photoData.DownloadStatus = PhotoDownloadStatus.DownloadFail_FileNotExists;
							photoData.PhotoBuffer = null;
							break;
						default :
							photoData.DownloadStatus = PhotoDownloadStatus.DownloadFail_NetworkError;
							photoData.PhotoBuffer = null;
							break;
					}
				}
			}
			catch (Exception ex)
			{
				photoData.DownloadStatus = PhotoDownloadStatus.DownloadFail_NetworkError;
				Log.Error(MethodBase.GetCurrentMethod().DeclaringType, "Failed to download photos!", ex);
			}
		}
	}
}
